package com.example.obs.config;

import com.example.obs.utils.ResponseUtil;
import com.example.obs.vo.ResultVO;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.ArrayList;
import java.util.List;

/**
 * SpringSecurity配置
 * 开启方法级安全，参数为EL表达式，参考下面链接
 * https://docs.spring.io/spring-security/site/docs/5.2.1.RELEASE/reference/html5/#el-access
 * @author Kevin
 * @date 2020-09-17 10:36
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 干掉自动配置
     * @see UserDetailsServiceAutoConfiguration
     **/
    @Bean
    UserDetailsService customUserDetailsService() {
        return s -> null;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .exceptionHandling()
                .accessDeniedHandler((httpServletRequest, httpServletResponse, e) -> ResponseUtil.response(ResultVO.error("该账号没有权限"), httpServletResponse, HttpStatus.OK.value()))
                .authenticationEntryPoint((request, response, e) -> ResponseUtil.response(ResultVO.error("请先登录"), response, HttpStatus.OK.value()))
        ;
        http.headers().frameOptions().disable();
    }


    /**
     * 获取权限
     * 懒得搞个工具类了，写在一块吧
     **/
    private static final List<GrantedAuthority> SP_ADMIN = new ArrayList<>(1);
    private static final List<GrantedAuthority> ADMIN = new ArrayList<>(1);
    private static final List<GrantedAuthority> USER = new ArrayList<>(1);
    static {
        // 超管
        SP_ADMIN.add(new SimpleGrantedAuthority("SP_ADMIN"));
        // 管理员
        ADMIN.add(new SimpleGrantedAuthority("ADMIN"));
        // 普通用户
        USER.add(new SimpleGrantedAuthority("USER"));
    }

    public static List<GrantedAuthority> authorities(Integer role) {
        switch (role) {
            case 2:
                return SP_ADMIN;
            case 1:
                return ADMIN;
            default:
                return USER;
        }
    }

}
